﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using One2One;
using Newtonsoft.Json;

namespace PluginService
{
    public class PluginServiceHelper:IDisposable
    {
        #region fileds

        protected static log4net.ILog _log = log4net.LogManager.GetLogger(typeof(PluginServiceHelper));

        protected int _port = 6001;

        protected string _extensionid = "halmbimoannfadoedalghfeihhjblaaj";

        protected bool _isInit = false;

        #endregion

        #region constructor

        public PluginServiceHelper()
        {
            
        }
        
        #endregion

        #region protected vitural methods

        protected virtual void HandOnReceivedSocketMessage(AsyncMessageHandleArgs<PluginRequestMessage> args)
        {
            if (args != null)
            {
                //byte[] sendData = Encoding.UTF8.GetBytes("33" + "\r\n");
                //args.AsyncSocketConnect.AsyncSend(sendData);
                if (args.Msg != null)
                {
                    args.Msg.SourceId = args.AsyncSocketConnect.ID;
                    HandMessage(args.Msg);
                }

            }
        }

        protected virtual void HandOnConnectedServer(AsyncSocketConnect<PluginRequestMessage> connect)
        {

        }

        protected virtual void HandMessage(PluginRequestMessage msg)
        {

            if (msg != null)
            {
                switch (msg.PluginMessageType)
                {
                    case PluginMessageType.One2OneByBase64:
                        OnReceivedOne2OneMsgByBase64(msg);
                        break;
                    case PluginMessageType.One2OneByUrl:
                        OnReceivedOne2OneMsgByUrl(msg);
                        break;
                    case PluginMessageType.AddBlank:
                        OnReceivedBlank(msg);
                        break;
                    case PluginMessageType.DetectiveFaceFeature:
                        break;
                    
                }
            }
        }

        protected virtual void OnReceivedDetectiveFaceFeatureMessage(PluginRequestMessage msg)
        {
            
        }

        protected virtual void OnReceivedBlank(PluginRequestMessage msg)
        {
 
        }

        protected virtual void OnReceivedOne2OneMsgByUrl(PluginRequestMessage msg)
        {
            if (msg.MessageBody != null)
            {
                FaceCompareResponse response = new FaceCompareResponse();
                var similar = One2OneHelper.Instance.GetSimlarByUrl(msg.MessageBody);
                if (similar < 0)
                {
                    response.result = false;
                    response.errorinfo = GetErrorInfor(similar);
                }
                else
                {
                    response.result = true;
                    response.similar = similar;
                }
                CommandCompleteHander(this, PluginMessageType.One2OneResponse, msg.SourceId, JsonConvert.SerializeObject(response));
            }
        }

        protected virtual void OnReceivedOne2OneMsgByBase64(PluginRequestMessage msg)
        {
            if (msg.MessageBody != null)
            {
                FaceCompareResponse response = new FaceCompareResponse();
                var similar = One2OneHelper.Instance.GetSimlarByBase64(msg.MessageBody);
                if (similar < 0)
                {
                    response.result = false;
                    response.errorinfo = GetErrorInfor(similar);
                }
                else
                {
                    response.result = true;
                    response.similar = similar;
                }
                CommandCompleteHander(this, PluginMessageType.One2OneResponse, msg.SourceId, JsonConvert.SerializeObject(response));
            }
        }

        protected virtual void CommandCompleteHander(object sender, PluginMessageType messageType, string soucrId, string msg)
        {
            if (!string.IsNullOrEmpty(soucrId))
            {
                if (!string.IsNullOrEmpty(soucrId))
                {

                    try
                    {
                        var socket = _socketServer.Connects[soucrId];
                        if (socket != null)
                        {
                            PluginResponseMessage response = new PluginResponseMessage();
                            response.PluginMessageType = messageType;
                            response.MessageBody = msg;
                            var creater = socket.IRecieveArgs;
                            if (creater != null)
                            {
                                socket.AsyncSend(socket.IRecieveArgs.CreateSendMsg(JsonConvert.SerializeObject(response)));
                            }

                        }
                    }
                    catch
                    {

                    }



                }

            }
        }

        #endregion

        #region private methods

        private string GetErrorInfor(float errCode)
        {
            string result = "未知错误";
            switch ((int)errCode)
            {
                case -1:
                    result = "Model不存在";
                    break;
                case -2:
                    result = "不支持此图片格式";
                    break;
                case -3:
                    result = "图片解析错误";
                    break;
                case -4:
                    result = "读取图片错误";
                    break;
                case -5:
                    result = "识别引擎创建失败";
                    break;
                case -6:
                    result = "句柄Handle错误";
                    break;
                case -7:
                    result = "人脸检测错误";
                    break;
                case -8:
                    result = "特征点获取失败";
                    break;


            }
            return result;
        }

        #endregion

        #region public methods

        public virtual void Init()
        {
            if (!_isInit)
            {
                string port = ConfigurationManager.AppSettings.Get("port");

                _extensionid = ConfigurationManager.AppSettings.Get("extensionid");
                if (!string.IsNullOrEmpty(port))
                {
                    _port = Convert.ToInt32(port);
                }

                _socketServer = new AsyncSocketServer<PluginRequestMessage>(_port, 10);
                _socketServer.OnReceivedMessage += new HandleMessageHandler<PluginRequestMessage>(HandOnReceivedSocketMessage);
                _socketServer.OnConnectedServer += new SocketConnectedHandler<PluginRequestMessage>(HandOnConnectedServer);
                _isInit = true;
            }
            
        }

        public virtual void Start()
        {
            _socketServer.InitSocket();
            _socketServer.Listen();
        }

        #endregion

        public void Dispose()
        {
            
        }
    }
}
